<template>
	<u-navbar title="" :is-back="true" :background="{}" class="bg" :borderBottom="false"></u-navbar>
	<view>
		<!-- <image class="image" :src="info.activity_images[0]"></image> -->
		<swiper class="image">
			<swiper-item v-for="(item,i) in info.activity_images" :key="i">
				<video v-if="isVideoFile(item)" id="myVideo" :src="item" style="width: 100%; height: 100%"
					object-fit="cover" :muted="true" autoplay loop :show-fullscreen-btn="false"
					:enable-progress-gesture="false" />
				<image v-else style="width: 100%; height: 100%" :src="item"></image>
			</swiper-item>
		</swiper>
		<view style="padding: 0 50rpx;">
			<view class="title">{{info.sub_title}}</view>
			<!-- <view class="time" style="margin-bottom: 30rpx;font-size: 28rpx;">副标题</view> -->
			<!-- <view class="time">— 5月29日 下午14:00-18:00 —</view> -->
			<!-- <view class="addr">
				地址: 高新区天府大道北段1777号大魔方招商花园城B馆二楼城市迷你奥特斯
			</view> -->
		</view>
		<view style="margin-bottom: 42rpx;overflow-x: auto;padding: 0 30rpx;">
			<rich-text :nodes="info.activity_dec"></rich-text>

		</view>
		<view class="images">
			<view>相关活动</view>
			<image style="width: 100vw;" v-for="(item,index) in info.relevant_activity" :key="item.id" :src="item.image"
				@click="skip(`/pages/common/activeDetails?id=${item.id}`)" mode="widthFix" />
		</view>

		<view style="position: fixed;bottom: 40rpx;width: 100%;left:calc(50% - 167rpx)" v-if="true">
			<view class="btn" @click="signIn">
				<i-icon icon="icon-baoming" size="24rpx" />
				立即报名
			</view>
		</view>
	</view>
	<u-popup v-model="show" mode="bottom" border-radius="60">
		<view style="padding: 60rpx 50rpx;max-height: 90vh;overflow-y: auto;">
			<view class="font-36 font-bold u-text-center">活动报名</view>
			<!-- <view
				style="background: #E5E5E5;width: 60rpx;height: 8rpx;position: absolute;top: 30rpx;left: calc(50% - 30rpx);">
			</view> -->
			<view style="margin: 50rpx 0;" class="font-32 font-bold">填写个人信息</view>
			<view class="phone flex flex-jc-sb flex-ai-c">
				<input v-model="form.member_phone" />
				<button @getphonenumber="getPhoneNumber" open-type="getPhoneNumber" class="buttom" type="primary"
					formType="submit">
					<view class="flex flex-ai-c flex-jc-c font-28" style="color: #333;">一键授权手机号</view>
				</button>
			</view>
			<view class="name flex flex-jc-sb" style="position: relative;">
				<input v-model="form.member_name" placeholder="姓名" />
				<view class="flex flex-jc-sb" @click="show2 = !show2"
					style="padding: 0 26rpx;width: 312rpx;height: 98rpx;border: 1rpx solid #E1E2DC;line-height: 98rpx;">
					{{form.member_sex}}
					<u-icon name="arrow-down" />
				</view>

				<block v-if="show2">
					<view style="position: absolute;top: 98rpx;right: 0;width: 312rpx;border: 1rpx solid #E1E2DC;">
						<view v-for="(item,i) in options" :key="i" @click="chosee(item)"
							style="height: 98rpx;color: #fff;background: #fff;line-height: 98rpx;padding: 0 26rpx;">
							<text :style="{'color': form.member_sex == item?'#2979ff':'#000'}">{{item}}</text>
						</view>
					</view>

				</block>
			</view>

			<view class="phone flex flex-jc-sb flex-ai-c mt-30">
				<input v-model="form.member_num" type="tel" />
				<view style="margin-right: 78rpx;" class="font-24">
					输入参与人数
				</view>
			</view>
			<view class="flex flex-ai-c flex-jc-sb" style="margin-top: 50rpx;">
				<view>{{info.join_money > 0 ? '￥' + totlaPrice() : '免费'}}</view>
				<!-- <view>{{totlaPrice()}}</view> -->
				<view class="submit" @click="activeCorder">提交</view>
			</view>
		</view>
	</u-popup>
	<loginPop :show="loginPopShow" @close="loginPopShow = false" />
</template>

<script setup lang="ts">
	import {
		ref, computed
	} from 'vue'
	import {
		onLoad, onShareAppMessage
	} from '@dcloudio/uni-app'
	import active from '../../api/active.js';
	import user from '../../api/user.js';
	import share from '../../utils/share.js'
	import loginPop from '@/components/loginPop.vue'
	let userinfo = uni.getStorageSync('userInfo')
	if (userinfo) userinfo.sex = userinfo.sex == 1 ? '男士' : '女士'
	let options = ref(['先生', '女士'])
	let show = ref(false)
	let show2 = ref(false)
	let id = ref(null)
	let isSkip = ref(1) //1跳转0返回
	let loginPopShow = ref(false)
	let form = ref({
		member_phone: userinfo.phone ? userinfo.phone : '',
		member_name: userinfo.auth_name ? userinfo.auth_name : '',
		member_sex: userinfo.sex ? userinfo.sex : '',
		member_num: 1,
		total_money: ''
	})
	let info = ref({ join_money: 0 })
	function isVideoFile(filename) {
		filename = typeof filename === 'string' ? filename : '';
		// 常见视频格式扩展名
		const videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm'];

		// 获取文件扩展名（转小写）
		const ext = filename.split('.').pop().toLowerCase();

		return videoExtensions.includes(ext);
	}
	const totlaPrice = computed(() => () => {
		let price = 0
		price = Number(info.value.join_money) * form.value.member_num
		form.value.total_money = formatAmount(price, '')
		return removeCommasAndParseToInt(formatAmount(price, ''))
	})
	const removeCommasAndParseToInt = (amountStr) => {
		// 去除金额字符串中的逗号
		let cleanAmountStr = amountStr.replace(/,/g, '');

		// 将处理后的字符串转换为整数类型
		let amountInt = Number(cleanAmountStr)

		return amountInt;
	}
	const formatAmount = (amount : number, currencySymbol : string, decimalPlaces = 2) => {
		return amount.toLocaleString('en-US', {
			style: 'decimal',
			minimumFractionDigits: decimalPlaces,
			maximumFractionDigits: decimalPlaces,
		}).replace(/\B(?=(\d{3})+(?!\d))/g, ',') + currencySymbol;
	}
	const skip = (url : string) => {
		uni.navigateTo({
			url: url
		})
	}

	//报名
	const signIn = async () => {
		if (!uni.getStorageSync('token')) return showMsg('请登录', () => {
			loginPopShow.value = true
		})
		// 没有订单--报名
		show.value = true
	}

	const getActiviteInfo = async (id : string | number) => {
		const res = await active.getActiviteInfo({
			id
		})
		// const regex = new RegExp('<img', 'gi')
		// res.data.activity_dec = res.data.activity_dec.replace(regex, `<img class="rich"`)
		info.value = res.data
	}
	//活动报名是否已报名
	const isJoinActive = async () => {
		const res = await active.isJoinActive({
			id: id.value,
			member_phone: form.value.member_phone
		})
		if (res.code === 401) {
			return res.code
		}
		if (res.code === 200) {//报名过
			return res.data
		} else if (res.code === 201) {
			showMsg(res.msg)
			return true
		} else {//没报名
			return false
		}
	}
	const showMsg = (title : string, success ?: AnyFunction) => {
		uni.showToast({
			title: title,
			icon: 'none',
			success: success
		})
	}
	//提交
	const activeCorder = async () => {
		if (!form.value.member_name || !form.value.member_phone || !form.value.member_sex || !form.value.member_num) return showMsg('请填写完整信息')
		//判断是否报名
		const data = await isJoinActive()
		if (data === 401) return loginPopShow.value = true

		if (data.id) {	//有订单未支付
			if (info.value.join_money == 0) return showMsg('您已申请过了，待支付')
			wxPay(data.id)
			return
		}
		if (data) return

		const res = await active.activeCorder({
			active_id: id.value,
			...form.value
		})
		if (res.code === 200) {
			if (info.value.join_money == 0) {
				if (isSkip.value) return skip(`/pages/me/activityOrders`)
				return uni.navigateBack()
			}
			wxPay(res.data.order_id)
		}
	}
	const wxPay = async (order_id : any) => {
		const res = await active.activePay({
			order_id: order_id
		})
		let payInfo : any = res.data.payRes
		uni.requestOrderPayment({
			...payInfo,
			success() {
				showMsg('支付成功')
				setTimeout(() => {
					if (isSkip.value) return skip(`/pages/me/activityOrders`)
					return uni.navigateBack()
				}, 1000)
			},
			fail(err2) {
				if (err2.errMsg === 'requestPayment:fail cancel') {
					showMsg('您已取消支付')
				} else {
					showMsg('支付失败')
				}
			}
		})
	}
	const getPhoneNumber = async (e) => {
		const res = await user.getPhoneNumber({
			code: encodeURIComponent(e.detail.code)
		})
		if (res.code !== 200) {
			showMsg(res.msg)
		} else {
			if (res.data.userInfo.sex == 1) {
				form.value.member_sex = '先生'
			} else if (res.data.userInfo.sex == 2) {
				form.value.member_sex = '女士'
			}
			form.value.member_phone = res.data.phoneNumber
			form.value.member_name = form.value.member_name ? form.value.member_name : res.data.userInfo.auth_name || ''
		}
	}
	const chosee = (v) => {
		form.value.member_sex = v
		show2.value = false
	}
	onShareAppMessage(() => {
		let str = `&id=${id.value}`
		return share(str, '', '')
	})
	onLoad((op : any) => {
		if (op.id) id.value = op.id
		if (op.skip) isSkip.value = Number(op.skip)
		getActiviteInfo(id.value)
	})
</script>

<style lang="scss" scoped>
	:deep(.rich) {
		max-width: 100vw !important;
	}

	.bg {
		width: 100%;
		height: 44rpx;
		position: absolute;
	}

	.title {
		font-weight: 600;
		font-size: 36rpx;
		color: #333333;
		text-align: center;
		margin: 58rpx 0 40rpx 0;
	}

	.image {
		width: 750rpx;
		height: 938rpx;
	}

	.phone {
		width: 100%;
		height: 98rpx;
		border: 1rpx solid #E1E2DC;

		input {
			padding-left: 26rpx;
		}

		.buttom {
			margin-right: 20rpx;
			width: 271rpx;
			height: 58rpx;
			background: #EBEAE6;
			line-height: 58rpx;
			text-align: center;
		}
	}

	.name {
		margin-top: 50rpx;

		input {
			width: calc(312rpx - 26rpx);
			height: 98rpx;
			border: 1rpx solid #E1E2DC;
			padding-left: 26rpx;
		}
	}

	.time {
		font-weight: 600;
		font-size: 24rpx;
		color: #000000;
		line-height: 24rpx;
		margin-bottom: 70rpx;
	}

	.addr {
		margin-bottom: 70rpx;
		font-weight: 400;
		font-size: 24rpx;
		color: #000000;
	}

	.images {
		view {
			font-weight: 600;
			font-size: 34rpx;
			color: #000000;
			margin: 109rpx 0 58rpx 0;
			text-align: center;
		}
	}

	.btn {
		width: 334rpx;
		height: 108rpx;
		background: #009943;
		border-radius: 54rpx;
		color: #fff;
		text-align: center;
		line-height: 108rpx;
		font-size: 24rpx;
	}

	.submit {
		width: 452rpx;
		height: 100rpx;
		background: #009943;
		border-radius: 50rpx;
		color: #fff;
		text-align: center;
		line-height: 100rpx;
	}
</style>